<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getHomeData } from "../../api/server";

const bannerUrl = ref("");
const productList = ref([] as any[]);
const promotionText = ref("");

const fetchHomeData = async () => {
  try {
    const response = await getHomeData();
    console.log("首页数据获取成功:", response);
    if (response.data.code === 200 && response.data.data) {
      const { list, banner } = response.data.data; // 解构出需要的数据
      bannerUrl.value = banner; // 直接使用返回的 banner 字符串
      productList.value = list.map((item: any) => ({
        id: item.tid,
        name: item.tname,
        price: parseFloat(item.price), // 使用后端返回的 price 字段
        image: `http://39.105.198.203:3001/${item.timg}`, // 拼接完整的图片 URL
        intro: item.tintro,
      }));
      promotionText.value = productList.value[0].intro || "茶叶促销中";
    }
  } catch (error) {
    console.error("获取首页数据失败:", error);
  }
};

onMounted(() => {
  fetchHomeData();
});
</script>

<template>
  <div class="home-page">
    <img :src="bannerUrl" alt="banner" class="banner" />

    <!-- 促销区域 -->
    <van-notice-bar :text="promotionText" />

    <!-- 精选好茶标题 -->
    <div class="section-title">
      <van-divider :content-position="'center'">精选好茶</van-divider>
    </div>

    <!-- 产品列表 -->
    <div class="product-grid">
      <van-grid :border="false" :column-num="2">
        <van-grid-item v-for="product in productList" :key="product.id">
          <div class="product-card">
            <van-image :src="product.image" />
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <p class="product-price">¥{{ product.price }}</p>
            </div>
          </div>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<style scoped>
.home-page {
  margin-bottom: 60px;
}

.banner {
  width: 95%;
  height: 200px;
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
}

.section-title {
  margin: 20px 0 15px;
  text-align: center;
}

.product-grid {
  padding: 0 10px;
}

.product-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-info {
  margin-top: 5px;
}

.product-name {
  font-size: 14px;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #e53935;
  font-size: 16px;
  font-weight: bold;
}
</style>
